package com.heartunderblade.rpc.loadbalancer;

import com.heartunderblade.rpc.RpcPojo.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinLoadBalancer implements LoadBalancer {
    /**
     * 轮询下标
     */
 private final AtomicInteger currentIndex =   new AtomicInteger(0);
    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if(serviceMetaInfoList.isEmpty()){
            return null;
        }

        int size = serviceMetaInfoList.size();
        if(size == 1 ){//只有一个服务无需轮询
            return serviceMetaInfoList.get(0);
        }
        //轮询就是进行取模运算
      int index =   currentIndex.getAndIncrement() % size;
        return serviceMetaInfoList.get(index);
    }
}
